package com.ms.convert.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public class MsOfficeKit {

    private static final int wdFormatPDF = 17;
    private static final int xlTypePDF = 0;
    private static final int ppSaveAsPDF = 32;

    public void convert2PDF(String inputFile, String pdfFile) {
        String suffix = getFileSufix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            System.out.println("文件不存在！");
            return;
        }
        if (suffix.equals("pdf")) {
            System.out.println("PDF not need to convert!");
            return;
        }
        boolean isImg = false;//FileUtils.isImage(inputFile);
        try {
            isImg = isImage(inputFile);
        } catch (Exception ce) {

        }
        if (isImg) {
//            img2PDF(inputFile, pdfFile);
        } else if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {
            word2PDF(inputFile, pdfFile);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            ppt2PDF(inputFile, pdfFile);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            excel2PDF(inputFile, pdfFile);
        } else if (suffix.equals("wps")) {
            //wps2PDF(inputFile,pdfFile);
            word2PDF(inputFile, pdfFile);
        } else {
            //System.out.println("文件格式不支持转换!");
            word2PDF(inputFile, pdfFile);
        }
    }


    public void convert2PDF(String inputFile) {
        String pdfFile = getFilePrefix(inputFile) + ".pdf";
        convert2PDF(inputFile, pdfFile);

    }


    public void convert2PDF(String[] inputFiles, String[] pdfFiles) {
        try {
            for (int i = 0; i < inputFiles.length; i++) {
                String inputFile = inputFiles[i];
                String pdfFile = pdfFiles[i];
                if (inputFile == null || inputFile.equals("")) {
                    continue;
                }
                convert2PDF(inputFile, pdfFile);
            }
        } catch (Exception ce) {

        }
    }

    public void convert2PDF(String[] inputFiles) {
        String pdfFiles[] = new String[inputFiles.length];
        for (int i = 0; i < inputFiles.length; i++) {
            String inputFile = inputFiles[i];
            String pdfFile = getFilePrefix(inputFile) + ".pdf";
            pdfFiles[i] = pdfFile;
        }
        convert2PDF(inputFiles, pdfFiles);
    }

    public static void word2PDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application"); //打开word应用程序
            app.setProperty("Visible", true); //设置word不可见
            Dispatch docs = app.getProperty("Documents").toDispatch(); //获得word中所有打开的文档,返回Documents对象
            //调用Documents对象中Open方法打开文档，并返回打开的文档对象Document
            doc = Dispatch.call(docs,
                    "Open",
                    inputFile,
                    false,
                    true
            ).toDispatch();
            Dispatch.call(doc,
                    "ExportAsFixedFormat",
                    pdfFile,
                    wdFormatPDF        //word保存为pdf格式宏，值为17
            );
        } catch (ComFailException e) {

        } catch (Exception e) {

        } finally {
            if (doc != null) {
                Dispatch.call(doc, "Close", false); //关闭文档
            }
            if (app != null) {
                app.invoke("Quit", 0); //关闭word应用程序
            }
            ComThread.Release();
        }
    }

    public static void excel2PDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch excel = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Excel.Application");
            app.setProperty("Visible", false);
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            excel = Dispatch.call(excels,
                    "Open",
                    inputFile,
                    false,
                    true
            ).toDispatch();
            Dispatch.call(excel,
                    "ExportAsFixedFormat",
                    xlTypePDF,
                    pdfFile
            );
        } catch (ComFailException e) {

        } catch (Exception e) {

        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }

    public static void ppt2PDF(String inputFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("PowerPoint.Application");
//            app.setProperty("Visible", true);
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            ppt = Dispatch.call(ppts,
                    "Open",
                    inputFile,
                    false,//ReadOnly
                    false //Untitled指定文件是否有标题
                    , false//WithWindow指定文件是否可见
            ).toDispatch();
            Dispatch.call(ppt, "SaveAs", pdfFile, ppSaveAsPDF);
        } catch (ComFailException e) {
            e.printStackTrace();
        } catch (Exception e) {

        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }

    public void wps2PDF(String inputFile, String pdfFile) {
        File sFile = new File(inputFile);
        File tFile = new File(pdfFile);
        ActiveXComponent wps = null;
        try {
            ComThread.InitSTA();
            wps = new ActiveXComponent("wps.application");
            ActiveXComponent doc = wps.invokeGetComponent("Documents").invokeGetComponent("Open", new Variant(sFile.getAbsolutePath()));
            doc.invoke("ExportPdf", new Variant(tFile.getAbsolutePath()));
            doc.invoke("Close");
            doc.safeRelease();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (wps != null) {
                wps.invoke("Terminate");
                wps.safeRelease();
            }
            ComThread.Release();
        }
    }

//    public void img2PDF(String inputFile, String pdfFile) {
//        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
//        try {
//            PdfWriter.getInstance(doc, new FileOutputStream(pdfFile));
//            doc.open();
//            doc.newPage();
//            Image img = Image.getInstance(inputFile);
//            float heigth = img.getHeight();
//            float width = img.getWidth();
//            int percent = getPercent(heigth, width);
//            img.setAlignment(Image.MIDDLE);
//            img.scalePercent(percent + 3);// 表示是原来图像的比例;
//            doc.add(img);
//            doc.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        File mOutputPdfFile = new File(pdfFile);
//        if (!mOutputPdfFile.exists()) {
//            mOutputPdfFile.deleteOnExit();
//            return;
//        }
//    }

    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    /**
     * 获取文件后缀的方法
     *
     * @return 文件后缀
     * @author https://www.4spaces.org/
     */
    public String getFileSufix(String name) {
        return name.substring(name.lastIndexOf(".") + 1);
    }

    private static String getFilePrefix(String inputFile) {
        int indexOf = StringUtils.lastIndexOf(inputFile, ".");
        return StringUtils.substring(inputFile, 0, indexOf);
    }


    private boolean isImage(String inputFile) {
        String fileSufix = getFileSufix(inputFile);
        return StringUtils.contains(fileSufix, "g");
    }

}
